﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.Models;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Entitys.System;
using SHZY.Systems.Interfaces.System;
using SHZY.Business.Entitys.Dto.QmsBusiWorkreport;
using SHZY.Business.Entitys;
using SHZY.Business.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace SHZY.Business;

/// <summary>
/// 业务实现：报工明细.
/// </summary>
[ApiDescriptionSettings(Tag = "Business", Name = "Workreport", Order = 200)]
[Route("api/Business/[controller]")]
public class QmsBusiWorkreportService : IQmsBusiWorkreportService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<QmsBusiWorkreportEntity> _repository;

    /// <summary>
    /// 数据接口服务.
    /// </summary>
    private readonly IDataInterfaceService _dataInterfaceService;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="QmsBusiWorkreportService"/>类型的新实例.
    /// </summary>
    public QmsBusiWorkreportService(
        ISqlSugarRepository<QmsBusiWorkreportEntity> qmsBusiWorkreportRepository,
        IDataInterfaceService dataInterfaceService,
        ISqlSugarClient context,
        IUserManager userManager)
    {
        _repository = qmsBusiWorkreportRepository;
        _dataInterfaceService = dataInterfaceService;
        _userManager = userManager;
    }

    /// <summary>
    /// 获取报工明细列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] QmsBusiWorkreportListQueryInput input)
    {
        var data = await _repository.Context.Queryable<QmsBusiWorkreportEntity, UserEntity>((a, b) => new JoinQueryInfos(JoinType.Left, a.OperatorId == b.Id))
            .WhereIF(!string.IsNullOrEmpty(input.workOrderId), a => a.WorkOrderId.Contains(input.workOrderId))
            .Where(a => a.DeleteMark == null)
            .OrderBy(a => a.CreatorTime)
            .Select((a, b) => new QmsBusiWorkreportListOutput
            {
                id = a.Id,
                workOrderId = a.WorkOrderId,
                operatorId = b.RealName,
                qty = a.Qty,
                ngQty = a.NgQty,
                actualStartTime = a.ActualStartTime,
                actualEndTime = a.ActualEndTime,
                workHours = a.WorkHours,
                status = a.Status,
                remark = a.Remark,
                creatorTime=a.CreatorTime
            }).ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<QmsBusiWorkreportListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建报工明细.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] QmsBusiWorkreportCrInput input)
    {
        var entity = input.Adapt<QmsBusiWorkreportEntity>();

        var isOk = await _repository.Context.Insertable(entity).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);

        // 更新工单实际开始时间
        var entity1 = await _repository.Context.Queryable<QmsBusiWorkreportEntity>().Where(x => x.WorkOrderId == entity.WorkOrderId && x.DeleteMark == null).OrderBy(x => x.ActualStartTime).FirstAsync();
        if (entity1 != null)
        {
            var isOk1 = await _repository.Context.Updateable<QmsBusiWorkorderEntity>().SetColumns(it => new QmsBusiWorkorderEntity()
            {
                ActualStartTime = entity1.ActualStartTime,
                LastModifyTime = DateTime.Now,
                LastModifyUserId = _userManager.UserId
            }).Where(x => x.Id == entity.WorkOrderId).ExecuteCommandHasChangeAsync();
            if (!isOk1)
                throw Oops.Oh(ErrorCode.COM1001);
        }

    }

    /// <summary>
    /// 删除报工明细.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Updateable<QmsBusiWorkreportEntity>().SetColumns(it => new QmsBusiWorkreportEntity()
        {
            DeleteTime = DateTime.Now,
            DeleteMark = 1,
            DeleteUserId = _userManager.UserId
        }).Where(x => x.Id == id).ExecuteCommandHasChangeAsync();
        if (!isOk) throw Oops.Oh(ErrorCode.COM1002);
    }
}